package com.example.dynamic;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.UiModeManager;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


import com.example.dynamic.util.DownloadUtil;
import com.example.dynamic.util.UnzipUtil;

import java.io.File;

import ohos.stage.ability.adapter.StageApplicationDelegate;

public class MainActivity extends Activity {

    private static String TAG = "MainActivity";
    private static final int UNZIP_FROM_ASSERT = 0;
    private static final int UNZIP_FROM_CLOUD = 1;

    Uri mUri;
    String mName;
    //是否正在下载
    private boolean isDownloading = false;
    private Button mButtonDown;
    private String mTargetPath;
    private static Context mContext;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.e("HiHelloWorld", "MainActivity onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mContext = this;
        mTargetPath = getFilesDir().getPath() + "/arkui-x";

        mButtonDown = findViewById(R.id.btn1);
        mButtonDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                downFileFromCloud();
            }
        });
        if(isFileExit()) {
            mButtonDown.setText("下载进度: " + 100 + "%");
        }

        Button btn2 = findViewById(R.id.btn2);
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
             StageApplicationDelegate applicationDelegate = new StageApplicationDelegate();
             applicationDelegate.initApplication(getApplication());
             Intent intent = new Intent(MainActivity.this, EntryEntryAbilityActivity.class);
             startActivity(intent);
            }
        });
    }

    /**
     * 从云端下载
     */
    private void downFileFromCloud() {
        if (isDownloading || isFileExit())
        {
            return;
        }
        String url = "https://data.ac-data.info/d324c040-04d1-4793-ab05-65b3f66a1fd4%2FzipContent.zip?Expires=1761551971&Key-Pair-Id=K3KM2F3CQPLOWK&Signature=oBUUJac~sfknmyA7i3fdbVet8DEhAyBAes7EHywK5L8qpBGlUnIooPFPeS3ZuJ6RKvU7jb6npLfbXybxcmCm7W35GtCOwB0w85JWq0sSL~mhOVjTafPbiInJVCfm08qY0IgdhjkwS6vZBbBUJdj9bpxixlgPCNIvIliod~1Zs8R8Mlw5oI94F2ZyfNHiCGOdCKqxMsoZaotW9jaHhHHYLvnNSid8W4qpyTVf~o0E6FkYQSP7UCPJL8CBSCHES6lH~PRASwEgujDRK-4HufXOHlmLo-jQscm4ay4K9eE74Vlnf~Qc22g8twz~VoJy5YHSwtgw9Xl5gC77-zx9gz4JDw__";
        String downFileName = "d324c040-04d1-4793-ab05-65b3f66a1fd4_zipContent.zip";
        String savePath = getFilesDir().getPath() + "/arkui-x";
        DownloadUtil.get().download(url, savePath, downFileName, new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess() {
                Log.i(TAG, "============下载完成");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
                        //待处理压缩文件路径
                        String zipPath = mTargetPath + "/" + downFileName;
                        //解压后要保存的目录
                        String outPath = mTargetPath;
                        //解压缩
                        unzip(zipPath, outPath, UNZIP_FROM_CLOUD);
                    }
                });
            }

            @Override
            public void onDownloading(int progress) {
                isDownloading = true;
                mButtonDown.setText("下载进度: " + progress + "%");
//                     Log.i("dyp","============"+progress);
            }

            @Override
            public void onDownloadFailed() {
                Log.i(TAG, "============下载失败");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        isDownloading = false;
                        mButtonDown.setText("云端请求下载");
                        Toast.makeText(MainActivity.this, "下载失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    /**
     * 解压缩
     *
     * @param zipPath     待解压文件
     * @param outPath     解压路径
     * @param unzipTagOne
     */
    private void unzip(String zipPath, String outPath, int unzipTagOne) {
        Log.d(TAG, "正在解压...");
        UnzipUtil.decompressFile(outPath,zipPath,new UnzipUtil.ZipResultCall() {
            @Override
            public void zipSuccessfUL(boolean isSuccessfUL) {
                if (isSuccessfUL) {
                    Toast.makeText(mContext, "解压成功", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "解压成功...");
                    isDownloading = false;

                } else {
                    Toast.makeText(mContext, "解压失败", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "解压失败...");
                }
            }
        });
    }
    public  boolean isFileExit() {
        File dir = new File(mTargetPath + "/arkui-x");
        return dir.exists();
    }


    /**
     * 删除文件夹和文件夹里面的文件
     *
     * @param dir
     */
    public static void deleteDirWihtFile(File dir) {
        if (dir == null || !dir.exists() || (!dir.isDirectory()&&!dir.isFile()))
            return;
        if (dir.isFile())
        {
            dir.delete();
        }else {
            for (File file : dir.listFiles()) {
                if (file.isFile())
                    file.delete(); // 删除所有文件
                else if (file.isDirectory())
                    deleteDirWihtFile(file); // 递规的方式删除文件夹
            }
            dir.delete();// 删除目录本身
        }
    }

}
